import React from "react"
import { Text, ScrollView, View } from "@tarojs/components"
import { Search, DropdownMenu, Cell, Sticky } from "@taroify/core"
import { Success } from "@taroify/icons"
import GpContainer from "@/components/GpContainer"
import GpIcon from "@/components/GpFontIcon"
import Taro, { pxTransform } from "@tarojs/taro"
import GpJumpNavs from "@/components/GpJumpNavs"
import GpCurrentPort from "@/components/GpCurrentPort"
import clsx from "clsx"
import GpTabbar from "@/components/GpTabbar"
import styles from "@/styles/common/top-fixed.module.scss"
import { getProFilters, getProList } from "@/apis/index"
import { pageMapper, PagePath, tabbarPages } from "@/constants/pageMap"
import { navigation } from "@/utils/router"
import GpEmpty from "@/components/GpEmpty"
import { setPageMeta } from "@/utils/common"
import GpScrollLoading from "@/components/GpScrollLoading"
import myStyles from "./index.module.scss"

const ports = [{ text: "专业大全" }]
const arrowSize = pxTransform(20)
type IState = {
  /** 过滤面板所选择的过滤项 */
  selectedFilterKey: any
  /** 学历层次 */
  levels: IDropDownFilterOption[]
  selectedLevel?: number
  /** 专业类别 */
  categorys: IDropDownFilterOption[]
  keyword: string
  pagination: IPagination
  list: any[]
  selectedFirstCate?: number | null
  lastCategorys: IDropDownFilterOption[]
  selectedLastCate?: number | null
  showLoading: boolean
}
type ICategorysMap = {
  [value: number]: IDropDownFilterOption[]
}
type IData = {
  categorysMap: ICategorysMap
  /** 查询参数 学历层次 */
  level?: number
  /**  for setPageInfo */
  pageMeta: {
    /**学历 */
    level: string
    /**专业类别  */
    category: string
    /** @ignore */
    pageLoaded: boolean
  }
}
const firstCategoryAllValue = 0
const non_lastCategoryAllValue = -9999
class Professional extends React.Component<unknown, IState> {
  extData: IData
  constructor(props) {
    super(props)
    this.state = {
      selectedFilterKey: false,
      levels: [],
      categorys: [],
      keyword: "",
      pagination: {
        page: 1,
        pageCount: 1
      },
      list: [],
      lastCategorys: [],
      selectedFirstCate: firstCategoryAllValue,
      selectedLastCate: non_lastCategoryAllValue,
      showLoading: false
    }
    this.extData = {
      categorysMap: {},
      pageMeta: {
        level: "",
        category: "",
        pageLoaded: false
      }
    }
  }
  onShareAppMessage() {}
  collectQuery = (options: Recordable) => {
    if (options.level) {
      this.extData.level = Number(options.level)
    }
  }
  onLoad(options: Recordable) {
    this.collectQuery(options)
    this.getDropdownFilters(this.extData.level).then(() => {
      this.search(1)
    })
  }
  componentDidShow() {
    this.setPageInfo()
  }
  setPageInfo = () => {
    const { level, category, pageLoaded } = this.extData.pageMeta
    if (pageLoaded) {
      setPageMeta({
        keywords: `${category}专业大全，${level}艺术专业`,
        description: `择艺宝为你整理${level}${category}专业大全与${level}${category}专业院校分布，让你快速查询到你想了解的专业与学校。`,
        title: `${level}${category}专业有哪些-${level}${category}专业院校推荐-择艺宝`
      })
    }
  }
  getPageInfo = (level?: INullable<number>, childCategory?: number) => {
    const { levels, lastCategorys } = this.state
    if (level) {
      const currentLelvel = levels.find(l => l.value === level)
      this.extData.pageMeta.level = currentLelvel?.text as string
    } else {
      // checked all
      this.extData.pageMeta.level = ""
    }
    if (childCategory) {
      const currentChildCategory = lastCategorys.find(l => l.value === childCategory)
      this.extData.pageMeta.category = currentChildCategory?.text as string
    } else {
      // checked all
      this.extData.pageMeta.category = "艺术"
    }
    this.extData.pageMeta.pageLoaded = true
    this.setPageInfo()
  }
  getDropdownFilters = level => {
    return new Promise(resolve => {
      getProFilters(level).then(res => {
        if (res.data.success) {
          const retData = res.data.data
          const categorysMap: ICategorysMap = {}
          const categorys: IDropDownFilterOption[] = (retData.categorys || []).map(l => {
            const childs = (l.childs || []).map(child => ({
              value: child.value,
              text: child.label
            }))
            categorysMap[l.value] = childs
            return {
              value: l.value,
              text: l.label
            }
          })
          this.extData.categorysMap = categorysMap
          const lastCategorys = categorysMap[this.state.selectedFirstCate as number] || []
          if (this.state.levels && this.state.levels.length > 0) {
            this.setState(
              {
                categorys,
                lastCategorys
              },
              () => {
                resolve(null)
              }
            )
          } else {
            const levels = (retData.levels || []).map(l => ({
              value: l.value,
              text: l.label
            }))
            let selectedLevel = levels[0].value
            if (level) {
              const finder = levels.find(l => l.value === level)
              if (finder) {
                selectedLevel = finder.value
              }
            }
            this.setState(
              {
                categorys,
                levels,
                selectedLevel,
                lastCategorys
              },
              () => {
                resolve(null)
              }
            )
          }
        }
      })
    })
  }
  search = (page = 1, showLoading = true) => {
    if (showLoading) {
      Taro.showLoading()
    }
    const { selectedLevel, keyword, selectedFirstCate, selectedLastCate } = this.state
    const params = {} as any
    if (selectedFirstCate !== firstCategoryAllValue) {
      params.cateId = selectedFirstCate
      if (selectedLastCate && selectedLastCate !== non_lastCategoryAllValue) {
        params.cateChildId = selectedLastCate
      }
    } else {
      // 不限
      if (selectedLastCate && selectedLastCate !== non_lastCategoryAllValue) {
        params.cateChildId = selectedLastCate
      }
    }
    this.getPageInfo(selectedLevel, params.cateChildId)
    return getProList({
      search: {
        level: selectedLevel,
        keyword,
        ...params
      },
      pagination: {
        current: page,
        pageSize: 10
      }
    })
      .then(res => {
        if (res.data.success) {
          const retData = res.data.data
          const retList = retData.list || []
          this.setState({
            list: page === 1 ? retList : this.state.list.concat(retList),
            pagination: {
              page: retData.pagination.current,
              pageCount: retData.pagination.pageCount
            },
            showLoading: retData.pagination.current + 1 <= retData.pagination.pageCount
          })
        }
      })
      .finally(() => {
        if (showLoading) {
          Taro.hideLoading()
        }
      })
  }
  onPullDownRefresh() {
    this.search(1, false).finally(() => {
      Taro.stopPullDownRefresh()
    })
  }
  onReachBottom() {
    console.info("到底了")
    const { pagination } = this.state
    if (pagination.page + 1 <= pagination.pageCount) {
      this.search(pagination.page + 1, true)
    }
  }
  handleDropdownMenuChange = (filterKey: any) => {
    this.setState({
      selectedFilterKey: filterKey
    })
  }
  /** 快捷导航 */
  renderJumpNavs = () => {
    return (
      <View className=" bg-white">
        {/* mt-20px */}
        <GpJumpNavs />
      </View>
    )
  }
  handleJump = (
    pagePath: PagePath,
    query: INullable<Recordable> = null,
    isTabbar = false,
    isPluginPath = false,
    isGpPluginPath = false
  ) => {
    navigation(pagePath, query, isTabbar ? "switchTab" : "navigateTo", isPluginPath, isGpPluginPath)
  }
  handleClickLevel = (item: IDropDownFilterOption) => {
    this.setState(
      {
        selectedLevel: item.value,
        selectedFirstCate: firstCategoryAllValue,
        selectedLastCate: non_lastCategoryAllValue
      },
      () => this.search(1)
    )
    this.getDropdownFilters(item.value)
    this.handleDropdownMenuChange(false)
  }
  handleKeywordChange = (ev: any) => {
    this.setState({
      keyword: ev.detail.value
    })
  }
  handleClickFirstCate = (item: IDropDownFilterOption) => {
    console.log("handleClickLevel----", item, this.extData.categorysMap)
    if (item.value !== firstCategoryAllValue) {
      this.setState({
        selectedFirstCate: item.value,
        lastCategorys: this.extData.categorysMap[item.value],
        selectedLastCate: non_lastCategoryAllValue
      })
    } else {
      // 不限
      this.setState({
        selectedFirstCate: firstCategoryAllValue,
        lastCategorys: this.extData.categorysMap[item.value],
        selectedLastCate: non_lastCategoryAllValue
      })
    }
  }
  handleClickLastCate = (item: IDropDownFilterOption) => {
    this.setState(
      {
        selectedLastCate: item.value
      },
      () => {
        this.search(1)
      }
    )
    this.handleDropdownMenuChange(false)
  }
  renderListTip = () => {
    const { list } = this.state
    console.log("renderListTip", list.length)
    if (list.length === 0) return null
    return (
      <View className="text-center yahei font-normal text-26px text-hex-666 leading-60px">
        暂无更多信息，看看别的内容吧~
      </View>
    )
  }
  render() {
    const {
      selectedFilterKey,
      levels,
      selectedLevel,
      keyword,
      categorys,
      selectedFirstCate,
      lastCategorys,
      selectedLastCate,
      list,
      showLoading
    } = this.state
    return (
      <GpContainer className="professional">
        <View className={styles["top-fixed"]}>
          <View className={styles["bg-wrap"]}>
            <View className="w-647px pt-32px mx-auto">
              <Search
                className={clsx(styles["search-input"], "search-input")}
                shape="round"
                placeholder="请输入搜索关键词"
                value={keyword}
                onChange={this.handleKeywordChange}
                onSearch={() => this.search(1)}
                clearable={false}
              />
            </View>
            <View className="flex flex-row justify-between px-52px mt-40px pb-32px">
              <View
                className="flex flex-col items-center leading-none"
                onClick={() => this.handleJump(pageMapper.proExplain)}
              >
                <GpIcon icon="icon-a-zhuanyejiedu_huaban1" color="#fff" size={44} />
                <Text className="yahei font-normal text-24px text-hex-fff pt-8px">专业解读</Text>
              </View>
              <View
                className="flex flex-col items-center leading-none"
                onClick={() =>
                  this.handleJump(tabbarPages.gpPluginInstitution, null, true, false, true)
                }
              >
                <GpIcon icon="icon-a-zhuanyejixun_huaban1" color="#fff" size={44} />
                <Text className="yahei font-normal text-24px text-hex-fff pt-8px">专业集训</Text>
              </View>
              <View
                className="flex flex-col items-center leading-none"
                onClick={() => this.handleJump(pageMapper.column, { sk: 1 })}
              >
                <GpIcon icon="icon-a-yikaozhuanti_huaban1" color="#fff" size={44} />
                <Text className="yahei font-normal text-24px text-hex-fff pt-8px">艺考专题</Text>
              </View>
              <View
                className="flex flex-col items-center leading-none"
                onClick={() => this.handleJump(pageMapper.news)}
              >
                <GpIcon icon="icon-a-yikaozixun_huaban1" color="#fff" size={44} />
                <Text className="yahei font-normal text-24px text-hex-fff pt-8px">艺考资讯</Text>
              </View>
            </View>
            <Sticky>
              {/* 下拉选择面板 */}
              <View catchMove>
                <DropdownMenu
                  value={selectedFilterKey}
                  onChange={this.handleDropdownMenuChange}
                  className={clsx(styles["filter-dropdown"], "filter-dropdown")}
                >
                  <DropdownMenu.Item title="学历层次">
                    <View className="flex-1 flex flex-col overflow-hidden">
                      <View className={myStyles["dropdown-list-content"]}>
                        <View className="flex-1">
                          <ScrollView
                            scrollY
                            style={{
                              height: "100%"
                            }}
                          >
                            {levels.map(l => (
                              <Cell
                                key={l.value}
                                title={l.text}
                                align="center"
                                clickable
                                onClick={() => this.handleClickLevel(l)}
                                className={clsx(styles["filter-dropdown-cell"], {
                                  [styles["checked"]]: l.value === selectedLevel
                                })}
                              >
                                {l.value === selectedLevel && (
                                  <Success color="#1A8CFF" style={{ fontSize: arrowSize }} />
                                )}
                              </Cell>
                            ))}
                          </ScrollView>
                        </View>
                      </View>
                    </View>
                  </DropdownMenu.Item>
                  <DropdownMenu.Item title="专业类别">
                    <View className="flex-1 flex flex-row overflow-hidden">
                      <View className="w-300px flex-none bg-hex-f5f5f5 overflow-auto">
                        <ScrollView
                          scrollY
                          style={{
                            height: "100%"
                          }}
                        >
                          {categorys.map(l => (
                            <View
                              key={l.value}
                              onClick={() => this.handleClickFirstCate(l)}
                              className={clsx(myStyles["filter-dropdown-first-cate"], {
                                [myStyles["checked"]]: l.value === selectedFirstCate
                              })}
                            >
                              {l.text}
                            </View>
                          ))}
                        </ScrollView>
                      </View>
                      <View className="flex-1 overflow-hidden">
                        <ScrollView
                          scrollY
                          style={{
                            height: "100%"
                          }}
                        >
                          {lastCategorys.map(l => (
                            <Cell
                              key={l.value}
                              title={l.text}
                              align="center"
                              clickable
                              onClick={() => this.handleClickLastCate(l)}
                              className={clsx(styles["filter-dropdown-cell"], {
                                [styles["checked"]]: l.value === selectedLastCate
                              })}
                            >
                              {l.value === selectedLastCate && (
                                <Success color="#1A8CFF" style={{ fontSize: arrowSize }} />
                              )}
                            </Cell>
                          ))}
                        </ScrollView>
                      </View>
                    </View>
                  </DropdownMenu.Item>
                </DropdownMenu>
              </View>
            </Sticky>
          </View>
        </View>
        {/* placeholoder */}
        {/* <View className="pt-396px"></View> */}
        {/* 列表内容 */}
        <View className="flex flex-col bg-hex-fff mt-20px pt-12px pb-24px">
          {list.length > 0 ? (
            list.map(l => (
              <View
                onClick={() => this.handleJump(pageMapper.proIntro, { id: l.id })}
                key={l}
                className={myStyles["list-item"]}
              >
                <View className="flex items-center justify-between">
                  <View className="yahei font-normal text-32px text-hex-2c2c35">
                    <Text>
                      {l.name}-{l.code}
                    </Text>
                  </View>
                  <View className="yahei font-normal text-24px text-hex-1a8cff">
                    <Text>开设院校：</Text>
                    <Text className="text-hex-1A8CFF">{l.schoolCount}</Text>
                  </View>
                </View>
                <View className="yahei mt-16px font-normal text-24px text-hex-b8b8bf">
                  <Text>专业类别：{l.cateName}</Text>
                </View>
              </View>
            ))
          ) : (
            <GpEmpty />
          )}
        </View>
        {showLoading ? (
          <GpScrollLoading />
        ) : (
          <React.Fragment>
            {this.renderListTip()}
            {/* 快捷导航 */}
            {this.renderJumpNavs()}
            {/* 当前位置 */}
            <GpCurrentPort ports={ports} />
          </React.Fragment>
        )}
        {/* 底部导航 */}
        <GpTabbar type={11} />
      </GpContainer>
    )
  }
}
export default Professional
